package com.joymart.recipient.service;

import com.joymart.common.error.handling.JoymartBusinessException;
import com.joymart.common.system.IdGenerator;
import com.joymart.common.utils.DatetimeUtils;
import com.joymart.common.utils.SecurityUtils;
import com.joymart.recipient.model.Recipient;
import com.joymart.recipient.repo.RecipientRepository;
import com.joymart.user.model.User;
import com.joymart.user.repo.UserRepository;
import com.joymart.user.service.UserCacheManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jdbc.core.JdbcAggregateTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RecipientService {

    @Autowired
    private RecipientRepository recipientRepository;
    @Autowired
    private CityService cityService;

    @Autowired
    private JdbcAggregateTemplate jdbcAggregateTemplate;

    @Autowired
    private IdGenerator idGenerator;
    @Autowired
    private UserCacheManager userCacheManager;
    @Autowired
    private UserRepository userRepository;

    // 保存新的Recipient
    public Recipient create(Recipient recipient) {
        recipient.setId(idGenerator.next());  // 确保id为空，系统生成新id
        String currentUserId = SecurityUtils.getCurrentUserId();
        recipient.setUserId(currentUserId);  // 设置当前用户ID
        recipient.setCreatedAt(DatetimeUtils.now());
        if (recipient.isAsDefault()) {
            resetDefault(recipient.getUserId());
            User user = userCacheManager.get(currentUserId).getUser();
            user.getMeta().put("city", cityService.parse(recipient.getDistrict()));
            userRepository.save(user);
        }

        return  jdbcAggregateTemplate.insert(recipient);
    }

    // 更新Recipient
    @Transactional
    public Recipient update(Recipient recipient) {
        if (recipient.isAsDefault()) {
            resetDefault(recipient.getUserId());
            String currentUserId = SecurityUtils.getCurrentUserId();
            User user = userCacheManager.get(currentUserId).getUser();
            user.getMeta().put("city", cityService.parse(recipient.getDistrict()));
            userRepository.save(user);
        }
        return jdbcAggregateTemplate.update(recipient);
    }

    // 根据ID删除Recipient
    public void delete(String id) {
        recipientRepository.deleteById(id);
    }

    // 根据ID查找Recipient
    public Recipient findById(String id) {
        return recipientRepository.findById(id).orElseThrow(()->new JoymartBusinessException("错误ID"));
    }

    // 根据userId查找所有属于该用户的Recipient
    public List<Recipient> findRecipientsByUserId(String userId) {
        return recipientRepository.findByUserId(userId);
    }

    // 将该用户Recipient的asDefault字段设置为false
    private void resetDefault(String userId) {
        List<Recipient> recipients = recipientRepository.findByUserId(userId);
        recipients.forEach(recipient -> {
            if (recipient.isAsDefault()) {
                recipient.setAsDefault(false);

                userCacheManager.invalidateUser(userId);
                recipientRepository.save(recipient);
            }
        });
    }
}